#include "uart.h"

void uart0_init() {
  GPHCON &= ~((0x3 << 4) | (0x3 << 6));
  GPHCON |= ((0x2 << 4) | (0x2 << 6));

  GPHUP &= ~((0x1 << 2) | (0x1 << 3));

  /* UBRDIVn = (int)( UART clock / ( buad rate x 16) ) –1 */
  UCON0 = 0x00000005;
  UBRDIV0 = 26;

  ULCON0 = 0x00000003;
}

int getchar() {
  while (!(UTRSTAT0 & (1 << 0)))
    ;
  return URXH0;
}

int putchar(int c) {
  while (!(UTRSTAT0 & (1 << 2)))
    ;
  UTXH0 = (unsigned char)c;
  return 0;
}

int puts(const char *s) {
  int i = 0;
  while (*s) {
    putchar(*s);
    s++;
    i++;
  }
  return i;
}

void printHex(uint val) {
  int i;
  uint8 arr[8];

  for (i = 0; i < 8; i++) {
    arr[i] = val & 0xf;
    val >>= 4;
  }

  puts("0x");
  for (i = 7; i >= 0; i--) {
    if (arr[i] >= 0 && arr[i] <= 9) {
      putchar(arr[i] + '0');
    } else if(arr[i] >= 0xA && arr[i] <= 0xF) {
			putchar(arr[i] - 0xA + 'A');
    }
  }
}

void print1() {
  puts("test 111\r\n");
}

void printSWIVal(unsigned int *pSWI) {
    unsigned int val = *pSWI & ~0xff000000;
    puts("SWI val = ");
    printHex(val);
    puts("\r\n");
}
